package su.msk.jet.team01.chatik.server;

import java.sql.SQLException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import su.msk.jet.team01.chatik.common.ArgsExtractor;
import su.msk.jet.team01.chatik.server.db.DatabaseAdapter;

public final class Main {
	private static DatabaseAdapter database = DatabaseAdapter.get();
	
	private static Logger logger = LoggerFactory.getLogger(Main.class);
	
	private static final int DEFAULT_PORT = 2005;

	/*
	 * Run as: java Main [-port port]
	 */

	private Main() {

	}

	public static void main(final String[] args) {
		ArgsExtractor argsExtractor = new ArgsExtractor(args);
		int port = stringToInt(argsExtractor.getArg("port"));
		boolean clear = argsExtractor.getArg("clear").equals("true");
		port = (validatePort(port) ? port : DEFAULT_PORT);
		
		if(clear) {
			clearDatabase();
		}
		createDatabaseEnvironment();
		
		Server.start(port);
	}

	private static int stringToInt(String arg) {
		try {
			return (arg == null ? -1 : Integer.valueOf(arg));
		} catch (NumberFormatException e) {
			return -1;
		}
	}

	private static boolean validatePort(int port) {
		final int maxPort = 65535;
		return (port >= 0 && port <= maxPort);
	}
	
	private static void clearDatabase() {
		try {
			database.execute("DROP VIEW history");
			database.execute("DROP TABLE messages");
			database.execute("DROP TABLE users");
		} catch (SQLException ex) {
			logger.error(ex.getMessage(), ex);
		}
	}
	
	private static void createDatabaseEnvironment() {
		try {
			database.execute(
					"CREATE TABLE users "
					+ "(id INT NOT NULL "
					+ "GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), "
					+ "name VARCHAR(100) NOT NULL)");
	
			database.execute(
					"CREATE TABLE messages "
					+ "(id INT NOT NULL "
					+ "GENERATED ALWAYS AS IDENTITY (START WITH 1, INCREMENT BY 1), "
					+ "date DATE NOT NULL, "
					+ "time TIME NOT NULL, "
					+ "from_user_id INT, to_user_id INT, "
					+ "message VARCHAR(1000) NOT NULL)");
	
			database.execute(
					"CREATE VIEW history AS "
					+ "SELECT msg.date date, msg.time time, user1.name sender, "
					+ "user2.name receiver, msg.message message FROM messages AS msg "
					+ "INNER JOIN users AS user1 ON msg.from_user_id=user1.id "
					+ "INNER JOIN users AS user2 ON msg.to_user_id=user2.id");
		} catch (SQLException ex) {
			logger.error(ex.getMessage(), ex);
		}
		
		
	}
}
